package sapling.logic.algorithm.pcb.queue;

public class Linked<T> {

	protected Node<T> head;
	protected int length;

	public Linked() {
		this.head = new Node<T>(true);
		this.length = 0;
	}

	public int size() {
		return this.length;
	}

	public boolean add(T data, int index) {
		if (index < 0)
			return false;
		if (index > this.length)
			index = this.length;
		Node<T> temp = this.head;
		for (int i = 0; i < index; i++, temp = temp.getNext())
			;
		temp.setNext(new Node<T>(temp, data, temp.getNext()));
		if (temp.getNext().getNext() != null)
			temp.getNext().getNext().setPrev(temp.getNext());
		this.length++;
		return true;
	}

	public boolean add(T data) {
		return add(data, this.length);
	}

	public T remove(int index) {
		if (index < 0 || index >= this.length || this.length == 0)
			return null;
		Node<T> temp = this.head;
		for (int i = 0; i < index; i++, temp = temp.getNext())
			;
		T data = temp.getNext().getData();
		if (temp.getNext().getNext() != null)
			temp.getNext().getNext().setPrev(temp);
		temp.setNext(temp.getNext().getNext());
		this.length--;
		return data;
	}
	
	public void removeAll() {
		this.head.setNext(null);
		this.length = 0;
	}

	/**
	 * 谨慎调用，确保参数属于该链表！
	 * 
	 * @param p
	 * @return
	 */
	public T removeNext(Node<T> p) {
		if (p == null || p.getNext() == null)
			return null;
		T data = p.getNext().getData();
		p.setNext(p.getNext().getNext());
		this.length--;
		return data;
	}

	public T get(int index) {
		if (index < 0 || index >= this.length || this.length == 0)
			return null;
		Node<T> temp = this.head;
		for (int i = 0; i <= index; i++, temp = temp.getNext())
			;
		return temp.getData();
	}

	public boolean isEmpty() {
		return this.length == 0;
	}

	public Node<T> getHead() {
		return this.head;
	}

}
